package com.sbl.bajw.pc.service;

import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sbl.bajw.common.ExcelUtil;
import com.sbl.bajw.common.MyBatisDao;
import com.sbl.bajw.common.web.BaiduMsgPush;
import com.sbl.bajw.common.web.MessageException;
import com.sbl.bajw.common.web.RequestUnit;
import com.sbl.bajw.common.web.SessionUnit;
import com.sbl.bajw.common.web.WebContext;
import com.sbl.bajw.mapper.LogTModelDao;
import com.sbl.bajw.mapper.OperationLogModelDao;
import com.sbl.bajw.mapper.TodoModelDao;
import com.sbl.bajw.mapper.TodoUserDao;
import com.sbl.bajw.pc.model.LogTModel;
import com.sbl.bajw.pc.model.OperationLogModel;
import com.sbl.bajw.pc.model.TodoModel;
import com.sbl.bajw.pc.model.TodoUserModel;
import com.sbl.bajw.util.FileUpload;
import com.sbl.bajw.util.LogUtil;

@Service
public class TodoService {
	
	@Resource
	private TodoModelDao dao;
	
	@Resource
	private TodoUserDao tuDao;
	
	@Resource 
	private MyBatisDao gridDao;
	
	@Resource
	private LogTModelDao logDao;

	@Resource
	private OperationLogModelDao op_dao;
	
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	static Logger log = null;
	
	static{
		log = LogUtil.getLogger("todo");
	}
	
	@Transactional(readOnly=false)
	public void Add(TodoModel model) throws MessageException{
		String todoId = dao.getId();
		String userId = SessionUnit.getUserId();
		
		model.setId(todoId);
		model.setCreateby(userId);
		dao.insertTodo(model);
		
		if(model.getUserids()!= null&&!model.getUserids().equals("")){
			String[] userids = model.getUserids().split(",",-1);
			String[] baiduUserids = model.getBaiduUserids().split(",",-1);
			String[] baiduChannelids = model.getBaiduChannelids().split(",",-1);
			for(int i = 0;i<userids.length;i++){
				String userid = userids[i];
				TodoUserModel tuModel = new TodoUserModel();
				tuModel.setTodoId(todoId);
				tuModel.setUserId(userid);
				tuDao.insert(tuModel);
				String baiduUserid = baiduUserids[i];
				String baiduChannelid = baiduChannelids[i];
				BaiduMsgPush.msgPush(baiduUserid, baiduChannelid, model.getContent(), model.getTitle());
			}
		}
		else{
			throw new MessageException("请选择执行人。");
		}
		
		//发送待办操作日志
		OperationLogModel entity = new OperationLogModel();
		entity.setOperationuserid(SessionUnit.getUserId());
		entity.setOperationcontent("发送待办");
		entity.setOperationname("发送待办");
		entity.setActionid("4");
		op_dao.insert(entity);
		
	}
	
	public void update(TodoModel model){
		dao.update(model);
		
		//修改待办信息操作日志
		OperationLogModel entity = new OperationLogModel();
		entity.setOperationuserid(SessionUnit.getUserId());
		entity.setOperationcontent("修改待办信息");
		entity.setOperationname("修改待办信息");
		entity.setActionid("3");
		op_dao.insert(entity);
	}
	
	public String getId(){
		String id = dao.getId();
		return id;
	}
	
	public String getList(HashMap<String, Object> parm){
		String json = gridDao.selectPage(TodoModelDao.class, parm, "getList");
		
		//待办列表查询操作日志
		OperationLogModel entity = new OperationLogModel();
		entity.setOperationuserid(SessionUnit.getUserId());
		entity.setOperationcontent("待办列表查询");
		entity.setOperationname("修改待办列表");
		entity.setActionid("3");
		op_dao.insert(entity);
		
		return json;
	}
	
	public void downList(HashMap<String, String> parm) throws Exception{
		List<HashMap<String, Object>> list = dao.getList(parm);
		HashMap<String, String> column = new HashMap<String, String>();
		column.put("TODO_CODE", "待办编号");
		column.put("TITLE", "标题");
		column.put("CONTENT", "内容");
		column.put("ADDRESS", "目标地址");
		column.put("CREATER", "创建人");
		column.put("CREATETIME", "创建时间");
		column.put("TODO_TYPE_NAME", "待办类型");
		column.put("TODO_LEVEL_TEXT", "紧急程度");
		column.put("TODO_USER_NAME", "执行人");
		column.put("END_TIME", "截止时间");
		column.put("FINISH_TIME", "完成时间");
		HttpServletResponse response = WebContext.getResponse();
		HSSFWorkbook wb = ExcelUtil.createExcel(list, column);
		OutputStream outStream = response.getOutputStream();
		response.setContentType("application/x-msdownload");  
		response.setHeader("Content-Disposition","attachment;filename=todo.xls");  
		wb.write(outStream);
		
		//待办列表导出操作日志
		OperationLogModel entity = new OperationLogModel();
		entity.setOperationuserid(SessionUnit.getUserId());
		entity.setOperationcontent("待办列表导出");
		entity.setOperationname("待办列表导出");
		entity.setActionid("5");
		op_dao.insert(entity);
	}
	
	public String getListByUser(){
		String userid = RequestUnit.getString("user_id");
		String is_finish = RequestUnit.getString("is_finish");
		HashMap<String, Object> parm = new HashMap<String, Object>();
		parm.put("user_id", userid);
		parm.put("is_finish", is_finish);
		String list = gridDao.selectPage(TodoModelDao.class, parm, "getListByUser");
		
		//APP查询待办列表操作日志
		OperationLogModel entity = new OperationLogModel();
		entity.setOperationuserid(userid);
		entity.setOperationcontent("APP待办列表查询");
		entity.setOperationname("APP待办列表查询");
		entity.setActionid("4");
		op_dao.insert(entity);
		
		return list;
	}
	
	public HashMap<String, String> getTodoCountByUser(String userid){
		HashMap<String, String> result = dao.getTodoCountByUser(userid);
		
		//APP查询待办总数操作日志
		OperationLogModel entity = new OperationLogModel();
		entity.setOperationuserid(userid);
		entity.setOperationcontent("APP待办总数查询");
		entity.setOperationname("APP待办总数查询");
		entity.setActionid("4");
		op_dao.insert(entity);
		
		return result;
	}
	
	public List<HashMap<String, String>> getTodoUser(String id){
		List<HashMap<String, String>> result = dao.getDetailUser(id);
		return result;
	}
	
	public HashMap<String, String> getModel(String id,String user_id){
		HashMap<String, String> parm = new HashMap<String, String>();
		parm.put("user_id", user_id);
		parm.put("todo_id", id);
		HashMap<String, String> model = dao.getDetail(parm);
		
		//APP待办详情查询操作列表
		OperationLogModel entity = new OperationLogModel();
		entity.setOperationuserid(user_id);
		entity.setOperationcontent("APP待办详情查询");
		entity.setOperationname("APP待办详情查询");
		entity.setActionid("4");
		op_dao.insert(entity);
		
		return model;
	}
	
	public void setReaded(String userid,String todoId){
		TodoUserModel model = new TodoUserModel();
		model.setTodoId(todoId);
		model.setUserId(userid);
		model.setIsReaded("1");
		tuDao.update(model);
		
		//APP待办详情查询操作列表
		OperationLogModel entity = new OperationLogModel();
		entity.setOperationuserid(userid);
		entity.setOperationcontent("APP修改待办阅读状态");
		entity.setOperationname("APP修改待办阅读状态");
		entity.setActionid("3");
		op_dao.insert(entity);
	}
	
	@Transactional
	public void finish() throws Exception{
		String userId = RequestUnit.getString("user_id");
		String todo_id = RequestUnit.getString("todo_id");
		Double x = RequestUnit.getDouble("x");
		Double y = RequestUnit.getDouble("y");
		String note = RequestUnit.getString("note");
		log.info("完成待办，userid："+userId+",todoid:"+todo_id);
		TodoUserModel tuModel = new TodoUserModel();
		tuModel.setTodoId(todo_id);
		tuModel.setUserId(userId);
		tuModel.setIsFinish("1");
		tuModel.setFinishX(x);
		tuModel.setFinishY(y);
		tuModel.setFinishNote(note);
		uploadFile(tuModel);
		tuDao.update(tuModel);

		LogTModel lt = new LogTModel();
		lt.setUserid(userId);
		lt.setCode("2");
		lt.setOperatingContent(sdf.format(new Date()) + "，" + userId + "完成待办。");
		
		logDao.insert(lt);
		
		//APP完成待办操作日志
		OperationLogModel entity = new OperationLogModel();
		entity.setOperationuserid(userId);
		entity.setOperationcontent("APP完成待办");
		entity.setOperationname("APP完成待办");
		entity.setActionid("3");
		op_dao.insert(entity);
	}
	 
	public void closeTodoByUser(String todoid,String userid){
		TodoUserModel tuModel = new TodoUserModel();
		tuModel.setTodoId(todoid);
		tuModel.setUserId(userid);
		tuModel.setStatus("0");
		tuDao.update(tuModel);
		
		//关闭待办操作日志
		OperationLogModel entity = new OperationLogModel();
		entity.setOperationuserid(SessionUnit.getUserId());
		entity.setOperationcontent("关闭某个人员待办");
		entity.setOperationname("关闭某个人员待办");
		entity.setActionid("3");
		op_dao.insert(entity);
	}
	
	public void uploadFile(TodoUserModel model) throws Exception{
		String id = UUID.randomUUID().toString();
		
		FileItem item = RequestUnit.getFileItem("img");
		String resultPath = "";
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmssS");
		
		if(item!=null)
		{
			String path = WebContext.getRequest().getSession().getServletContext().getInitParameter("UploadPath");
			String dataStr = sf.format(Calendar.getInstance().getTime());
			resultPath = "images/todofinish/"+FileUpload.saveFile(item, path+"/images/todofinish/",dataStr+"_img_"+id);
			model.setFinishImg(resultPath);
			log.info("收到图片："+resultPath);
		}
		else{
			log.info("没有图片");
		}
		
		FileItem itemvoice = RequestUnit.getFileItem("voice");
		String resultPathVoice = "";
		
		if(itemvoice!=null)
		{
			String path = WebContext.getRequest().getSession().getServletContext().getInitParameter("UploadPath");
			String dataStr = sf.format(Calendar.getInstance().getTime());
			resultPathVoice = "images/todofinish/"+FileUpload.saveFile(itemvoice, path+"/images/todofinish/",dataStr+"_voice_"+id);
			model.setFinishVoice(resultPathVoice);
			log.info("收到录音："+resultPathVoice);
		}
		else{
			log.info("没有录音");
		}
	}

}
